package org.mathcloud.math.core.scilab.operator.algebra;

import org.apache.log4j.Logger;
import org.mathcloud.math.core.common.operator.algebra.Inverse;
import org.mathcloud.math.core.scilab.factory.ScilabQuantityObjectFactory;
import org.mathcloud.math.core.scilab.manager.ScilabSupervisor;
import org.mathcloud.math.core.scilab.operator.ScilabUnaryOperator;
import org.mathcloud.math.core.scilab.quantity.ScilabQuantityObject;
import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.types.ScilabDouble;

public class ScilabInverse extends ScilabUnaryOperator implements Inverse
{
	public ScilabInverse()
	{
		super();
		signature.setMMLContentTag("inverse");
	}
	
	@Override
	public void calculate()
	{
		if (getResultSignature()!=null)
    {
      String sciJob;
      String tmpVar = "tmp_"+ScilabSupervisor.getVarId();
			ScilabQuantityObject tOp1 = ScilabQuantityObjectFactory.getInstance(operand);
			sciJob = tmpVar;
			sciJob = sciJob + "=1/"+ tOp1.getVarName()+";";
      if (sciEngine.exec(sciJob))
      {
      	log.info(sciJob);
      	try
				{
      		ScilabDouble tRes = (ScilabDouble)sciEngine.get(tmpVar);
	      	res = ScilabQuantityObjectFactory.getInstance(tRes);
					sciJob = "clear "+tmpVar+";";
					if (sciEngine.exec(sciJob))
						log.info(sciJob);					      	
				} catch (JavasciException e)
				{
					log.error(e);
				}
      }
      else
      {
      	res = null;
      	log.info(sciJob);
      	log.info(sciEngine.getLastErrorMessage());
      }
    }    		
	}

	private static final Logger log = Logger.getLogger(ScilabInverse.class);
}
